﻿using Cache.CSRedis;
using Common.Tools;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Order.Common
{
    public class RedisConcurrentDictionary
    {
        static ConcurrentDictionary<string, CsRedisHelper> redisDictionary = new ConcurrentDictionary<string, CsRedisHelper>();
        static List<string> nodes = new List<string>();
        public static void InitRedisInstance(List<RedisOptions> options)
        {
            if (!options.Any())
            {
                throw new Exception("Redis的配置参数不能为空!");
            }
            nodes = options?.Select(e => e.HostName).ToList();
            foreach (var option in options)
            {
                var redisInstance = new CsRedisHelper(option);
                var result = redisDictionary.TryAdd(option.HostName, redisInstance);
                if (!result)
                {
                    throw new Exception($"初始化Redis实例失败!实例名称:{option.HostName}");
                }
            }
        }

        public static CsRedisHelper GetRedisInstance(string redisKey)
        {
            KetamaNodeLocator ketamaNodeLocator = new KetamaNodeLocator(nodes);
            var node = ketamaNodeLocator.GetPrimary(redisKey);
            CsRedisHelper csRedisHelper;
            var result = redisDictionary.TryGetValue(node, out csRedisHelper);
            if (!result)
            {
                throw new Exception($"一致性Hash获取Redis实例失败!实例名称:{node}");
            }
            return csRedisHelper;
        }

    }
}
